package com.wzu.servlet;

import com.wzu.pojo.Category;
import com.wzu.service.CategoryService;
import com.wzu.service.CategoryServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/getCategories")
public class CategoryServlet extends HttpServlet {
    private CategoryService categoryService = new CategoryServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        List<Category> categoryList = categoryService.getCategories();

        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < categoryList.size(); i++) {
            Category category = categoryList.get(i);
            json.append("{");
            json.append("\"category_id\":").append(category.getCategory_id()).append(",");
            json.append("\"category_name\":\"").append(category.getCategory_name()).append("\"");
            json.append("}");
            if (i < categoryList.size() - 1) {
                json.append(",");
            }
        }
        json.append("]");

        out.write(json.toString());
        out.flush();
        out.close();
    }
}